<template>
  <div style="height: 100%; position: relative" @click="hideContextMenu">
    <!-- 右键菜单组件 -->
    <div
      v-if="contextMenu.visible"
      :style="{
        position: 'fixed',
        left: contextMenu.x + 'px',
        top: contextMenu.y + 'px',
        zIndex: 1000
      }"
      class="context-menu"
    >
      <div class="menu-header">
        <span>{{ contextMenu.node?.title }}</span>
      </div>
      <div class="menu-divider"></div>

      <!-- 连接节点菜单 -->
      <div v-if="contextMenu.node?.type === 'connection'">
        <div class="menu-item" @click="handleConnect">
          <LinkOutlined class="menu-icon" />
          <span>连接</span>
        </div>
        <div class="menu-item" @click="handleEditConnection">
          <EditOutlined class="menu-icon" />
          <span>编辑连接</span>
        </div>
        <div class="menu-item" @click="handleDeleteConnection">
          <DeleteOutlined class="menu-icon" />
          <span>删除连接</span>
        </div>
        <div class="menu-divider"></div>
        <div class="menu-item" @click="handleConnectionInfo">
          <InfoCircleOutlined class="menu-icon" />
          <span>连接信息</span>
        </div>
      </div>

      <!-- 数据库节点菜单 -->
      <div v-if="contextMenu.node?.type === 'database'">
        <div class="menu-item" @click="handleUseDatabase">
          <DatabaseOutlined class="menu-icon" />
          <span>使用数据库</span>
        </div>
        <div class="menu-item" @click="handleShowCreateDatabase">
          <CodeOutlined class="menu-icon" />
          <span>查看建库语句</span>
        </div>
        <div class="menu-divider"></div>
        <div class="menu-item" @click="handleDeleteDatabase">
          <DeleteOutlined class="menu-icon" />
          <span>删除数据库</span>
        </div>
      </div>

      <!-- 超级表节点菜单 -->
      <div v-if="contextMenu.node?.type === 'supertable'">
        <div class="menu-item" @click="handleShowCreateTable">
          <CodeOutlined class="menu-icon" />
          <span>查看建表语句</span>
        </div>
        <div class="menu-item" @click="handleQueryTable">
          <SearchOutlined class="menu-icon" />
          <span>新建查询</span>
        </div>
        <div class="menu-item" @click="handleQueryTableData">
          <SearchOutlined class="menu-icon" />
          <span>查看数据</span>
        </div>
        <div class="menu-item" @click="handleExportTable">
          <ExportOutlined class="menu-icon" />
          <span>导出数据</span>
        </div>
        <div class="menu-divider"></div>
        <div class="menu-item" @click="handleDeleteTable">
          <DeleteOutlined class="menu-icon" />
          <span>删除表</span>
        </div>
      </div>

      <!-- 子表节点菜单 -->
      <div v-if="contextMenu.node?.type === 'table'">
        <div class="menu-item" @click="handleQueryTable">
          <SearchOutlined class="menu-icon" />
          <span>查询数据</span>
        </div>
        <div class="menu-item" @click="handleShowTableStructure">
          <PartitionOutlined class="menu-icon" />
          <span>查看表结构</span>
        </div>
        <div class="menu-item" @click="handleExportTable">
          <ExportOutlined class="menu-icon" />
          <span>导出数据</span>
        </div>
      </div>
    </div>

    <div v-if="treeData.length > 0">
      <div>
        <a-tree
          :tree-data="treeData"
          :load-data="onLoadData"
          :expanded-keys="expandedKeys"
          @expand="onExpand"
          @select="handleClick"
        >
          <template #title="{ key, title, type }">
            <span
              class="tree-node-title"
              @contextmenu.prevent="showContextMenu($event, { key, title, type })"
            >
              <component :is="getIcon(type)" style="margin-right: 5px; color: #3370ff" />
              {{ title }}
              <span v-if="type === 'supertable'" class="table-count">
                ({{ getTableCount(key) }})
              </span>
            </span>
          </template>

          <template #switcherIcon="{ expanded, dataRef }">
            <span v-if="dataRef.type === 'more'">⬇️</span>
            <LoadingOutlined v-else-if="loadingKeys.includes(dataRef.key)" />
            <CaretDownFilled v-else-if="expanded" />
            <CaretRightFilled v-else />
          </template>
        </a-tree>
      </div>
    </div>
    <div v-else style="height: 100%; display: flex; justify-content: center; align-items: center">
      <a-empty description="暂无连接配置" />
    </div>
  </div>

  <a-modal v-model:open="treeNodeVisible" :title="treeNodeModalTitle" @ok="handleOk">
    <p>{{ treeNodeCreateInfo }}</p>
  </a-modal>
</template>

<script setup>
import { ref, defineExpose, onMounted, nextTick } from 'vue'
import {
  CaretDownFilled,
  CaretRightFilled,
  LoadingOutlined,
  LinkOutlined,
  DatabaseOutlined,
  PartitionOutlined,
  TableOutlined,
  EditOutlined,
  DeleteOutlined,
  InfoCircleOutlined,
  CodeOutlined,
  SearchOutlined,
  ExportOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useMainStore } from '../store'
import { useRouter } from 'vue-router'

const router = useRouter()
const mainStore = useMainStore()
const { ipcRenderer } = window.electron
const treeData = ref([])
const expandedKeys = ref([])
const loadingKeys = ref([])
const tableCounts = ref({})
const contextMenu = ref({
  visible: false,
  x: 0,
  y: 0,
  node: null
})
const treeNodeVisible = ref(false)
const treeNodeModalTitle = ref('')
const treeNodeCreateInfo = ref({})
// 显示右键菜单
const showContextMenu = (event, node) => {
  contextMenu.value = {
    visible: true,
    x: event.clientX,
    y: event.clientY,
    node: node
  }
}

// 隐藏右键菜单
const hideContextMenu = () => {
  contextMenu.value.visible = false
}

// 节点类型对应的图标
const getIcon = (type) => {
  const icons = {
    connection: LinkOutlined,
    database: DatabaseOutlined,
    supertable: PartitionOutlined,
    table: TableOutlined,
    more: TableOutlined
  }
  return icons[type] || TableOutlined
}

// 获取超级表下的子表数量
const getTableCount = (key) => {
  return tableCounts.value[key] || '...'
}

// 点击节点事件
const handleClick = async (selectedKeys, { node }) => {
  const nodeData = node.dataRef
  if (nodeData.type === 'database') {
    await ipcRenderer.send('setValue', 'thisDatabase', JSON.stringify(nodeData))
  }
  hideContextMenu() // 点击节点时隐藏菜单
}

// =============== 右键菜单功能实现 ===============

// 连接操作
const handleConnect = () => {
  message.info(`连接: ${contextMenu.value.node.title}`)
  // 实际实现: 调用连接TDengine的IPC方法
  hideContextMenu()
}

// 编辑连接
const handleEditConnection = () => {
  message.info(`编辑连接: ${contextMenu.value.node.title}`)
  hideContextMenu()
}

// 删除连接
const handleDeleteConnection = () => {
  message.info(`删除连接: ${contextMenu.value.node.title}`)
  hideContextMenu()
}

// 连接信息
const handleConnectionInfo = () => {
  message.info(`查看连接信息: ${contextMenu.value.node.title}`)
  hideContextMenu()
}

// 使用数据库
const handleUseDatabase = () => {
  message.info(`使用数据库: ${contextMenu.value.node.title}`)
  // 实际实现: 执行USE database命令
  hideContextMenu()
}

// 查看建库语句
const handleShowCreateDatabase = () => {
  message.info(`查看建库语句: ${contextMenu.value.node.title}`)
  // 实际实现: 执行SHOW CREATE DATABASE命令
  hideContextMenu()
}

// 删除数据库
const handleDeleteDatabase = () => {
  message.info(`删除数据库: ${contextMenu.value.node.title}`)
  // 实际实现: 执行DROP DATABASE命令
  hideContextMenu()
}

// 查看建表语句
const handleShowCreateTable = async () => {
  // console.log(contextMenu.value.node,'contextMenu.value.node')
  const sql = `SHOW CREATE TABLE ${contextMenu.value.node.title}`
  const res = await ipcRenderer.invoke('doQuery', sql)
  treeNodeVisible.value = true
  treeNodeCreateInfo.value = res[0][1]
  treeNodeModalTitle.value = res[0][0] + ' 建表语句'
  hideContextMenu()
}

// 新建查询
const handleQueryTable = () => {
  message.info(`查询数据: ${contextMenu.value.node.title}`)
  // 实际实现: 打开查询界面并自动填充SELECT语句
  router.push('/query')
  hideContextMenu()
}

// 查询表数据
const handleQueryTableData = () => {
  const keyArray = contextMenu.value.node.key.split('/')
  // mainStore.selectedComponent = {
  //   currentDatabase: keyArray[0],
  //   currentTable: keyArray[2]
  // }
  router.push({
    path: '/tableData',
    query: {
      currentDatabase: keyArray[0],
      currentTable: keyArray[2]
    }
  })
  hideContextMenu()
}

// 导出表数据
const handleExportTable = () => {
  message.info(`导出数据: ${contextMenu.value.node.title}`)
  // 实际实现: 调用数据导出功能
  hideContextMenu()
}

// 查看表结构
const handleShowTableStructure = () => {
  message.info(`查看表结构: ${contextMenu.value.node.title}`)
  // 实际实现: 执行DESCRIBE命令
  hideContextMenu()
}

// 删除表
const handleDeleteTable = () => {
  message.info(`删除表: ${contextMenu.value.node.title}`)
  // 实际实现: 执行DROP TABLE命令
  hideContextMenu()
}

// =============== 树结构相关方法 ===============
// 加载更多子表
const loadMoreTables = async (node) => {
  const { database, supertable, page } = node
  loadingKeys.value.push(node.key)

  try {
    // 切换到目标数据库
    await ipcRenderer.invoke('doQuery', `USE ${database}`)

    // 查询下一页的子表数据
    const nextPage = page + 1
    const offset = (nextPage - 1) * 100
    const query = `
      SELECT table_name
      FROM information_schema.ins_tables
      WHERE db_name = '${database}'
        AND stable_name = '${supertable}'
      ORDER BY create_time desc LIMIT 100
      OFFSET ${offset}
    `

    const res = await ipcRenderer.invoke('doQuery', query)

    // 创建子表节点
    const childTables = res.map((item) => ({
      title: item[0],
      key: `${database}/${supertable}/table/${item[0]}`,
      type: 'table',
      isLeaf: true
    }))

    // 更新当前节点的children
    const parentNode = findNode(treeData.value, node.parentKey)
    if (parentNode) {
      // 移除"加载更多"节点
      parentNode.children = parentNode.children.filter((child) => child.type !== 'more')

      // 添加新的子表节点
      parentNode.children = [...parentNode.children, ...childTables]

      // 如果还有更多数据，添加新的"加载更多"节点
      if (childTables.length === 100) {
        parentNode.children.push({
          title: '加载更多...',
          key: `${database}/${supertable}/more/${nextPage}`,
          type: 'more',
          database: database,
          supertable: supertable,
          page: nextPage,
          parentKey: parentNode.key
        })
      }
    }
  } catch (error) {
    console.error('加载子表失败:', error)
    message.error(`加载子表失败: ${error.message}`)
  } finally {
    loadingKeys.value = loadingKeys.value.filter((key) => key !== node.key)
  }
}

// 递归查找节点
const findNode = (nodes, targetKey) => {
  for (const node of nodes) {
    if (node.key === targetKey) {
      return node
    }
    if (node.children) {
      const found = findNode(node.children, targetKey)
      if (found) return found
    }
  }
  return null
}

// 树节点加载数据
const onLoadData = async (treeNode) => {
  const node = treeNode.dataRef
  if (node.loaded) return Promise.resolve()

  loadingKeys.value.push(node.key)

  try {
    if (node.type === 'connection') {
      await getDatabasesList(node)
    } else if (node.type === 'database') {
      await getSuperTablesList(node)
    } else if (node.type === 'supertable') {
      await getChildTables(node)
    } else if (node.type === 'more') {
      await loadMoreTables(node)
    }

    node.loaded = true
    return Promise.resolve()
  } catch (error) {
    console.error('加载数据失败:', error)
    message.error(`加载数据失败: ${error.message}`)
    return Promise.reject(error)
  } finally {
    loadingKeys.value = loadingKeys.value.filter((key) => key !== node.key)
  }
}

// 获取当前连接下的数据库列表
const getDatabasesList = async (node) => {
  console.log(node, 'node')
  const res = await ipcRenderer.invoke('getConnInfo')
  if (!res) {
    const connList = await ipcRenderer.invoke('getValue', 'connList')
    if (!connList) {
      message.error('请先添加连接')
    } else {
      const list = JSON.parse(connList)
      for (const item of list) {
        if (item.connectionName + '/conn' === node.key) {
          const connFlag = await ipcRenderer.invoke('connectToTDengine', JSON.stringify(item))
          console.log('connFlag', connFlag)
          if (!connFlag) {
            message.error('连接失败，请重启软件')
          }
        }
      }
    }
  }

  try {
    const sql = `SHOW DATABASES;`
    const sqlRes = await ipcRenderer.invoke('doQuery', sql)

    const databases = sqlRes.map((item) => ({
      title: item[0],
      key: `${node.title}/database/${item[0]}`,
      type: 'database',
      isLeaf: false,
      loaded: false,
      children: []
    }))

    node.children = databases
  } catch (error) {
    console.error('获取数据库列表失败:', error)
    message.error(`获取数据库列表失败: ${error.message}`)
  }
}

// 获取数据库下的超级表
const getSuperTablesList = async (node) => {
  try {
    const dbName = node.title
    await ipcRenderer.invoke('doQuery', `USE ${dbName}`)
    const sql = `SHOW STABLES;`
    const sqlRes = await ipcRenderer.invoke('doQuery', sql)

    const superTables = sqlRes.map((item) => ({
      title: item[0],
      key: `${dbName}/supertable/${item[0]}`,
      type: 'supertable',
      isLeaf: false,
      loaded: false,
      children: []
    }))

    // 同时获取每个超级表下的子表数量
    await getTableCounts(dbName, superTables)

    node.children = superTables
  } catch (error) {
    console.error('获取超级表列表失败:', error)
    message.error(`获取超级表列表失败: ${error.message}`)
  }
}

// 获取每个超级表下的子表数量
const getTableCounts = async (dbName, superTables) => {
  try {
    for (const table of superTables) {
      const query = `
        SELECT COUNT(*)
        FROM information_schema.ins_tables
        WHERE db_name = '${dbName}'
          AND stable_name = '${table.title}'
      `
      const res = await ipcRenderer.invoke('doQuery', query)
      if (res && res.length > 0) {
        tableCounts.value[table.key] = res[0][0]
      }
    }
  } catch (error) {
    console.error('获取表数量失败:', error)
  }
}

// 获取超级表下的子表（分页）
const getChildTables = async (node) => {
  try {
    const dbName = node.key.split('/')[0]
    const stableName = node.title

    await ipcRenderer.invoke('doQuery', `USE ${dbName}`)

    // 查询第一页的子表数据
    const query = `
      SELECT table_name
      FROM information_schema.ins_tables
      WHERE db_name = '${dbName}'
        AND stable_name = '${stableName}'
      ORDER BY create_time desc LIMIT 100
    `

    const res = await ipcRenderer.invoke('doQuery', query)

    // 创建子表节点
    const childTables = res.map((item) => ({
      title: item[0],
      key: `${dbName}/${stableName}/table/${item[0]}`,
      type: 'table',
      isLeaf: true
    }))

    // 添加子表节点
    node.children = childTables

    // 如果还有更多数据，添加"加载更多"节点
    if (res.length === 100) {
      node.children.push({
        title: '加载更多...',
        key: `${dbName}/${stableName}/more/2`,
        type: 'more',
        database: dbName,
        supertable: stableName,
        page: 2,
        parentKey: node.key
      })
    }
  } catch (error) {
    console.error('获取子表列表失败:', error)
    message.error(`获取子表列表失败: ${error.message}`)
  }
}

// 获取本地连接列表
const getLocalConnList = async () => {
  try {
    const res = await ipcRenderer.invoke('getValue', 'connList')
    if (res) {
      try {
        const list = JSON.parse(res)
        const values = list.map((item) => ({
          title: item.connectionName,
          key: `${item.connectionName}/conn`,
          type: 'connection',
          isLeaf: false,
          loaded: false,
          children: []
        }))

        treeData.value = values
      } catch (e) {
        console.error('解析 JSON 失败:', e)
      }
    }
  } catch (err) {
    console.error('IPC 调用失败:', err)
  }
}

// 展开节点事件
const onExpand = (expandedKeysValue) => {
  expandedKeys.value = expandedKeysValue
}

onMounted(async () => {
  await getLocalConnList()

  // 添加全局点击事件监听，点击页面其他区域隐藏菜单
  document.addEventListener('click', hideContextMenu)
})

defineExpose({ getLocalConnList })
</script>

<style scoped>
.tree-node-title {
  display: flex;
  align-items: center;
  padding: 4px 8px;
  border-radius: 4px;
}

.tree-node-title:hover {
  background-color: #f0f7ff;
}

.table-count {
  margin-left: 8px;
  font-size: 12px;
  color: #888;
}

/* 右键菜单样式 */
.context-menu {
  background-color: white;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  box-shadow:
    0 3px 6px -4px rgba(0, 0, 0, 0.12),
    0 6px 16px 0 rgba(0, 0, 0, 0.08),
    0 9px 28px 8px rgba(0, 0, 0, 0.05);
  min-width: 180px;
  overflow: hidden;
}

.menu-header {
  padding: 8px 12px;
  font-weight: 600;
  background-color: #f5f5f5;
  border-bottom: 1px solid #f0f0f0;
}

.menu-divider {
  height: 1px;
  background-color: #f0f0f0;
  margin: 4px 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #f5f5f5;
}

.menu-icon {
  margin-right: 8px;
  color: #555;
  font-size: 14px;
}

:deep(.ant-tree-treenode) {
  padding: 4px 0;
  width: 100%;
}

:deep(.ant-tree-node-content-wrapper) {
  display: flex;
  align-items: center;
  width: calc(100% - 24px);
}

:deep(.ant-tree-switcher) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.ant-tree-title) {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.ant-tree-indent-unit) {
  width: 16px;
}
</style>
